package com.czk.gulimall.ware.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czk.common.exception.NoStockException;
import com.czk.common.to.mq.OrderTo;
import com.czk.common.to.mq.StockDetailTo;
import com.czk.common.to.mq.StockLockTo;
import com.czk.common.utils.PageUtils;
import com.czk.common.utils.Query;
import com.czk.common.utils.R;
import com.czk.gulimall.ware.dao.WareSkuDao;
import com.czk.gulimall.ware.entity.WareOrderTaskDetailEntity;
import com.czk.gulimall.ware.entity.WareOrderTaskEntity;
import com.czk.gulimall.ware.entity.WareSkuEntity;
import com.czk.gulimall.ware.feign.OrderFeignService;
import com.czk.gulimall.ware.feign.ProductFeignService;
import com.czk.gulimall.ware.listener.StockReleaseListener;
import com.czk.gulimall.ware.service.WareOrderTaskDetailService;
import com.czk.gulimall.ware.service.WareOrderTaskService;
import com.czk.gulimall.ware.service.WareSkuService;
import com.czk.gulimall.ware.vo.OrderItemVo;
import com.czk.gulimall.ware.vo.SkuHasStockVo;
import com.czk.gulimall.ware.vo.WareSkuLocVo;
import com.rabbitmq.client.Channel;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service("wareSkuService")
@RabbitListener(queues = "stock.release.stock.queue")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {
    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private WareOrderTaskService wareOrderTaskService;
    @Autowired
    private WareOrderTaskDetailService wareOrderTaskDetailService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private StockReleaseListener stockReleaseListener;



    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)) {
            wrapper.eq("sku_id", skuId);
        }
        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)) {
            wrapper.eq("ware_id", skuId);
        }
        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    /**
     * 锁定库存
     *
     * @param skuId
     * @param wareId
     * @param skuNum
     */
    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        // 先查找
        WareSkuEntity wareSkuEntity = this.baseMapper.selectOne(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        // 拿到数目
        if (wareSkuEntity == null) {
            // 新增
            wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStockLocked(0);
            // sku信息
            try {
                // try的目的是为了不让异常回滚，以为这个对业务的要求不是很高，如果回滚则代价太大了
                R info = productFeignService.info(skuId);
                Map<String, Object> map = (Map<String, Object>) info.get("skuInfo");
                wareSkuEntity.setSkuName((String) map.get("skuName"));
            } catch (Exception e) {
                e.printStackTrace();
            }
            this.baseMapper.insert(wareSkuEntity);
        } else {
            // 更新
            wareSkuEntity.setStock(wareSkuEntity.getStock() + skuNum);
            this.baseMapper.updateById(wareSkuEntity);
        }
    }

    @Override
    public List<SkuHasStockVo> getSkuHasStock(List<Long> skuIds) {

        List<SkuHasStockVo> collect = skuIds.stream().map(skuId -> {
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("sku_id", skuId);
            List<WareSkuEntity> wareSkuEntities = this.baseMapper.selectList(wrapper);
            long stock = 0;
            if (wareSkuEntities != null && wareSkuEntities.size() > 0) {
                for (WareSkuEntity wareSkuEntity : wareSkuEntities) {
                    // 当前库存减去锁定库存
                    stock += wareSkuEntity.getStock() - wareSkuEntity.getStockLocked();
                }
            }
            skuHasStockVo.setSkuId(skuId);
            skuHasStockVo.setHasStock(stock > 0);
            return skuHasStockVo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * @param vo
     * @return
     */
    @Override
    @Transactional(rollbackFor = NoStockException.class)
    public Boolean orderLockStock(WareSkuLocVo vo) {
        // 为订单锁库存保存信息
        WareOrderTaskEntity orderTaskEntity = new WareOrderTaskEntity();
        orderTaskEntity.setOrderSn(vo.getOrderSn());
        // 保存库存工作单信息
        wareOrderTaskService.save(orderTaskEntity);


        // 为某个订单锁定库存
        List<OrderItemVo> locks = vo.getLocks();

        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            SkuWareHasStock stock = new SkuWareHasStock();
            Long skuId = item.getSkuId();
            // 查看在哪些仓库有库存
            List<Long> wareIds = this.baseMapper.listWareIdHasStock(skuId);
            stock.setWareId(wareIds);
            stock.setNum(item.getCount());
            return stock;
        }).collect(Collectors.toList());

        for (SkuWareHasStock hasStock : collect) {
            Boolean skuStocked = false;
            Long skuId = hasStock.getSkuId();
            // 扣除锁定的库存
            List<Long> wareIds = hasStock.getWareId();
            if (wareIds == null || wareIds.size() == 0) {
                // 没库存异常
                throw new NoStockException(skuId);
            }
            // 如果每一个商品都锁定成功，将当前商品锁定了几件工作单记录发给mq
            // 锁定失败，前面保存的工作单信息就回滚了，即使要解锁，由于查不到数据库id，也不会解锁
            for (Long wareId : wareIds) {
                // 锁定库存 成功返回1否则是0
                long count = this.baseMapper.lockSkuStock(skuId, wareId, hasStock.getNum());
                if (count == 1) {
                    // 锁定成功
                    skuStocked = true;
                    WareOrderTaskDetailEntity orderTaskDetailEntity = new WareOrderTaskDetailEntity(
                            null,
                            skuId,
                            null,
                            hasStock.getNum(),
                            orderTaskEntity.getId(),
                            wareId,
                            1
                    );
                    // 保存工作单详情
                    wareOrderTaskDetailService.save(orderTaskDetailEntity);
                    // 发送消息，告诉mq锁定了一些库存
                    StockLockTo lockTo = new StockLockTo();
                    lockTo.setId(orderTaskEntity.getId());
                    //
                    StockDetailTo stockDetailTo = new StockDetailTo();
                    BeanUtils.copyProperties(orderTaskDetailEntity, stockDetailTo);
                    lockTo.setDetail(stockDetailTo);
                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", lockTo);
                    break;
                }
                log.info("继续下个仓库锁定");
            }
            if (!skuStocked) {
                // 当前商品所有仓库没锁住
                throw new NoStockException(skuId);
            }
        }
        return true;
    }

    @Data
    class SkuWareHasStock {
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }

    /**
     * 防止订单五福卡顿，导致订单状态一直改不了
     * 库存消息优先到期，查订单状态新建导致库存不能释放
     * @param orderTo
     */
    @Override
    public void unlockStock(OrderTo orderTo) {
        String orderSn = orderTo.getOrderSn();
        // 查一下库存解锁状态
       WareOrderTaskEntity wareOrderTaskEntity= wareOrderTaskService.getOrderTaskByOrderSn(orderSn);
       Long id = wareOrderTaskEntity.getId();
       // 按照工作单找到没有解锁的库存
        List<WareOrderTaskDetailEntity> list = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>().eq("task_id", id).eq("lock_status", 1));
        // 解锁
        for (WareOrderTaskDetailEntity orderTaskDetailEntity : list) {
            stockReleaseListener.unLockStock(orderTaskDetailEntity.getSkuId(),
                    orderTaskDetailEntity.getWareId(),
                    orderTaskDetailEntity.getSkuNum(),
                    orderTaskDetailEntity.getTaskId());
        }
    }
}